const ws=require('ws');
const fs=require('fs');
const net = require('net');
const http = require('http');
const https = require('https');
const config = require(`./${process.env.CONFIG}`);
const {send_success,send_error,set_uuid} = require(`./commit.js`);

//设置证书
const keypath=process.cwd()+'/pem/server.pem';
const certpath=process.cwd()+'/pem/server.crt';
let options = {
  key: fs.readFileSync(keypath),
  cert: fs.readFileSync(certpath),
  passphrase:''//如果秘钥文件有密码的话，用这个属性设置密码
};
//启动http服务
http.createServer(function(req, res){
    res.writeHead(403);
    res.end('这是http协议，不是websocke协议!\n');

}).listen(config.http_port);
//启动https服务
var server = https.createServer(options, function (req, res) {
    res.writeHead(403);//403即可
    res.end("这是https协议，不是websocke协议!\n");
}).listen(config.https_port);


net.createServer(function(socket){
    socket.once('data', function(buf){
        // https数据流的第一位是十六进制“16”，转换成十进制就是22
        console.log(buf.toString());

        var address = buf[0] === 22 ? config.https_port : config.http_port;
        //创建一个指向https或http服务器的链接
        var proxy = net.createConnection(address, function() {
            proxy.write(buf);
            //反向代理的过程，tcp接受的数据交给代理链接，代理链接服务器端返回数据交由socket返回给客户端
            socket.pipe(proxy).pipe(socket);
        });
        proxy.on('error', function(err) {
            console.log(err);
        });
    });
    
    socket.on('error', function(err) {
        console.log(err);
    });
}).listen(config.port);
console.log(`server启动 //127.0.0.1:${config.port}`)
console.log(`wss启动 wss://127.0.0.1:${config.https_port}`)


// var server=http.createServer(options, function (req, res) {
//     res.writeHead(403);//403即可
//     res.end("不是websocke协议!\n");
// }).listen(config.port);
// console.log(`server启动   ${process.env.AGREE}://127.0.0.1:${config.port}`)

//启动ws
var wss = new ws.Server( { server: server } );
wss.on( 'connection', function ( wsConnect ) {
    //接受消息
    wsConnect.on( 'message', async function ( message ) {
        try {
            send_success(wsConnect,"连接成功！");
            console.log( message );
            let result = JSON.parse(message);
            if(result.type == undefined || result.type == ''){
                await send_error(wsConnect,"请求类型不能为空！");
                return;
            }
            switch(result.type){
                case 'login' :
                    //登录
                    if(result.uuid == undefined || result.uuid === ''){
                        await send_error(wsConnect,"登录uuid不能为空！");
                        break;
                    }
                    wsConnect.id = result.uuid;
                    await send_success(wsConnect,"登录成功！");
                    break;
                case 'getData' :
                    //获取数据
                    let data = {
                        uuid:result.uuid,
                        msg:'这是数据'
                    };
                    //返回给对应的用户
                    await send_success(wsConnect,"请求成功",data);
                    break;
                case 'zhiding' :
                    //指定用户发送某个消息
                    if(result.uuid == undefined || result.uuid === ''){
                        await send_error(wsConnect,"指定用户uuid不能为空！");
                        break;
                    }

                    break;
                default :
                    await send_error(wsConnect,"类型不存在！");
            }
            
        } catch (error) {
            console.log( `业务处理异常[${error}]` );
        }
    });

    //连接关闭
    wsConnect.on('close',function(err){
        console.log(wsConnect.id);
        console.log(err);
        console.log("连接关闭!");
    })

    //连接异常
    wsConnect.on('error',function(err,code,reason){
        console.log(err);
        console.log(code);
        console.log(reason);
        console.log("连接异常!");
    })

});
